package io.renren.common.session;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.Assert;
import redis.clients.jedis.JedisShardInfo;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Created by luzhenting on 2017/11/27.
 */
public class ClusterConfiguration {

    /**
     * 客户端连接超时时间
     */
    @Value("${redis.connectionTimeout}")
    private Integer redisConnectionTimeout;
    /**
     * 客户端读写超时时间
     */
    @Value("${redis.soTimeout}")
    private String redisSoTimeout;

    private List<JedisShardInfo> shards;

    public void setShards(List<JedisShardInfo> shards) {
        this.shards = shards;
    }

    public List<JedisShardInfo> getShards() {
        return shards;

    }

    public ClusterConfiguration(Collection<String> clusterNodes){
        Assert.notEmpty(clusterNodes,"redis clusterNodes must not be empty!");
        this.shards=ClusterConfiguration.converCollectionToSet(clusterNodes);
    }

    public ClusterConfiguration(String clusterNodes){
        Assert.notNull(clusterNodes,"redis clusterNodes must not be null!");
        this.shards = ClusterConfiguration.converStringToSet(clusterNodes);
    }

    public static List<JedisShardInfo> converCollectionToSet(Collection<String> clusterNodes){
        List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
        JedisShardInfo shardInfo = null;
        for (String node: clusterNodes){
            String[] info = node.split(":");
            shardInfo = new JedisShardInfo(info[0],Integer.valueOf(info[1]));
            shards.add(shardInfo);
        }
        return shards;
    }

    public static List<JedisShardInfo> converStringToSet(String clusterNodes){
        List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
        String[] nodes = clusterNodes.split(",");
        for (String n: nodes){
            String[] info = n.split(":");
            JedisShardInfo shardInfo = new JedisShardInfo(info[0],Integer.valueOf(info[1]));
            shards.add(shardInfo);
        }
        return shards;
    }
}
